<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace plugins\crawler\controller; //Demo插件英文名，改成你的插件英文就行了

use cmf\controller\PluginAdminBaseController;
use think\Db;

use plugins\crawler\model\CrawlerRuleModel;
use plugins\crawler\model\CrawlerSiteModel;
use plugins\crawler\model\CrawlerUrlModel;
use plugins\crawler\model\DictionaryModel;
use app\portal\model\PortalCategoryModel;


class AdminUrlController extends PluginAdminBaseController
{

    protected function _initialize()
    {
        parent::_initialize();
        $adminId = cmf_get_current_admin_id();//获取后台管理员id，可判断是否登录
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        }
    }

    /**
     * 采集列表
     * @adminMenu(
     *     'name'   => '采集列表',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '采集列表',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $crawlerSiteId      = $this->request->param('crawler_site_id', 0, 'intval');
        $crawlerUrlModel = new CrawlerUrlModel();
        $crawlerSiteModel = new CrawlerSiteModel();

        $site = $crawlerSiteModel->find($crawlerSiteId);

        //category
        $urls = $crawlerUrlModel
            ->where(['crawler_site_id' => $crawlerSiteId])
            ->paginate();
        
        // 获取分页显示
        $page = $urls->render();

        //var_dump($rules[0]->category);die;

        //$sites = Db::name("crawler_site")->all();
        //$demos = PluginDemoModel::all();

        // print_r($demos);

        $this->assign("siteid", $crawlerSiteId);
        $this->assign("site", $site);
        $this->assign("urls", $urls);
        $this->assign("page", $page);

        return $this->fetch('/admin_url');
    }


    /**
     * 采集列表
     * @adminMenu(
     *     'name'   => '通过规则添加采集列表',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '采集列表',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        $crawlerRuleId      = $this->request->param('crawler_rule_id', 0, 'intval');

        $crawlerRuleModel = new CrawlerRuleModel();

        $crawlerRule = $crawlerRuleModel->find($crawlerRuleId);
        $crawlerSiteModel = new CrawlerSiteModel();

        $site = $crawlerSiteModel->find($crawlerRule->crawler_site_id);

        $listurl =  $crawlerRule->listpath;

        $times = preg_match_all('/\{([^\}]+?)\}/', $crawlerRule->listpath, $matches);

        $parameters = [];
        
        foreach($matches[1] as $i => $val)
        {
            $parameter = explode(':', $val);
            $parameter[1] = isset($parameter[1]) ? $parameter[1] : '';
            $parameters[$parameter[0]] = $parameter[1];
            $listurl = preg_replace('/\{'. $parameter[0] .'(:[^\}]+)?\}/', $parameter[1], $listurl) ;
        }

        $this->assign("listurl", $listurl);
        $this->assign("site", $site);
        $this->assign("siteid", $site->id);
        $this->assign("parameters", $parameters);
        $this->assign("crawlerRule", $crawlerRule);

        return $this->fetch('/admin_url_add');
    }

    /**
     * 编辑采集列表
     * @adminMenu(
     *     'name'   => '编辑采集列表',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '采集列表',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $id      = $this->request->param('id', 0, 'intval');

        $crawlerRuleModel = new CrawlerRuleModel();
        $crawlerUrlModel = new CrawlerUrlModel();
        $crawlerSiteModel = new CrawlerSiteModel();

        $crawlerUrl = $crawlerUrlModel->find($id);

        $crawlerRule = $crawlerRuleModel->find($crawlerUrl->crawler_rule_id);
        
        $site = $crawlerSiteModel->find($crawlerRule->crawler_site_id);

        $this->assign("site", $site);
        $this->assign("siteid", $site->id);
        $this->assign("crawlerRule", $crawlerRule);
        $this->assign("crawlerUrl", $crawlerUrl);
        
        return $this->fetch('/admin_url_edit');
    }


    /**
     * 保存采集列表
     * @adminMenu(
     *     'name'   => '保存采集列表',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '保存采集列表',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        if ($this->request->isPost()) {
            
            $result = $this->validate($this->request->param(), 'CrawlerUrl');
            
            if ($result !== true) {
                $this->error($result);
            }

            $post = $this->request->param();

            $crawlerRule = CrawlerRuleModel::get($post['crawler_rule_id']);
            $crawlerSite = CrawlerSiteModel::get($crawlerRule->crawler_site_id);

            $data['listurl']         = $crawlerRule->listpath;
            $data['crawler_rule_id'] = $crawlerRule->id;
            $data['crawler_site_id'] = $crawlerRule->crawler_site_id;
        
            if(array_key_exists('parameters', $post)) 
            {
                foreach($post['parameters'] as $key => $val)
                {
                    if($crawlerSite->charset != 'utf-8')
                    {
                        $val = mb_convert_encoding($val, $crawlerSite->charset, 'utf-8');
                    }
                    $data['listurl'] = preg_replace('/\{'. $key .'(:[^\}]+)?\}/', urlencode($val), $data['listurl']) ;
                }
            }
            $data['listurl'] = $crawlerRule->baseuri. $data['listurl'];
            $data['create_time'] = time();

            if ($result !== true) {
                // 验证失败 输出错误信息
                $this->error($result);
            } else {
                $result = DB::name('crawler_url')->insert($data);
                if ($result !== false) {
                    $this->success("保存成功！");
                } else {
                    $this->error("保存失败！");
                }
            }
            
        }
    }

    /**
     * 保存采集列表
     * @adminMenu(
     *     'name'   => '保存采集列表',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '保存采集列表',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        if ($this->request->isPost()) {
            
            $id      = $this->request->param('id', 0, 'intval');

            $data['listurl'] = stripslashes($this->request->param('listurl'));
            
            if (!$id) {
                $this->error('参数非法');
            } else {
                
                $result = DB::name('crawler_url')->where(['id' => $id])->update($data);

                if ($result !== false) {
                    $this->success("保存成功！");
                } else {
                    $this->error("保存失败！");
                }
            }
            
        }
    }


    /**
     * 删除采集列表
     * @adminMenu(
     *     'name'   => '删除采集列表',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除采集列表',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $intId = $this->request->param("id", 0, 'intval');

        if (empty($intId)) {
            $this->error(lang("NO_ID"));
        }
        $crawlerUrlModel = new CrawlerUrlModel();

        $collCount = Db::name('crawler_collection')->where('crawler_url_id', $intId)->count();
        
        if($collCount) {
            $this->error(lang("请先删除采集数据"));
        }
        else
        {
            $crawlerUrlModel->where(['id' => $intId])->delete();
            $this->success(lang("DELETE_SUCCESS"));
        }
    }

}
